<?php

namespace App\Http\Controllers\Web\Activity;

use App\App\Services\PrizeStockService;
use App\App\Services\StorageService;
use App\App\Services\Web\ActivityService;
use App\App\Services\Web\UserService;
use App\Events\ActivityPaused;
use App\Events\ActivityStarted;
use App\Events\RouletteUpdated;
use App\Events\ScratchUpdated;
use App\Events\ShakingUpdated;
use App\Events\GoldenEggsUpdated;
use App\Events\ActivityCommonUpdated;
use App\Exceptions\ExceptionCode;
use App\Http\Controllers\Controller;
use App\Models\Activity\Activity;
use App\Models\Activity\ActivityService as ActivityServiceModel;
use App\Contracts\Repositories\ActivityRepository;
use App\Models\ActivityInfo\ActivityInfoService;
use App\Models\ActivityModel\ActivityModelService;
use App\Models\ActivityModel\ActivityModelRepository;
use App\Models\ActivityModelTemplate\ActivityModelTemplateService;
use App\Models\ActivityPrize\ActivityPrizeService;
use App\Models\ActivityRecord\ActivityRecord;
use App\Models\ActivityRecord\ActivityRecordService;
use App\Models\PrizeRecord\PrizeRecordService;
use App\Models\VoteCandidate\VoteCandidateService;
use App\Models\VoteGroup\VoteGroupService;
use App\Morefun\Publishing\Publisher;
use App\Morefun\Wechat\Service as WechatService;
use Illuminate\Container\Container;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Models\VoteCandidate\VoteCandidateRepository;
use  App\Models\VoteGroup\VoteGroupRepository;
use Maatwebsite\Excel\Facades\Excel;
use Ramsey\Uuid\Uuid;

class ActivityController extends Controller
{


    /**
     * @var array 活动分类
     */
    private $type = [
        'enroll' => '投票',
    ];

    /**
     *
     * 利用providers 加载多个活动的serivce，实现每个活动各自的业务独立
     *
     * @param $name
     *
     * @return bool|\Illuminate\Foundation\Application|false
     */
    public function getInstanceof($name)
    {
        return isset($this->type[$name]) ? app($name) : false;
    }

    public function activity(
        Request $request,
        ActivityService $activityService,
        UserService $userService,
        ActivityPrizeService $activityPrizeService,
        ActivityInfoService $activityInfoService,
        StorageService $storageService,
        VoteCandidateRepository $voteCandidateRepository,
        VoteGroupRepository $voteGroupRepository
    )
    {
        if ($request->isMethod('post')) {
            $this->validate($request, [
                'category'    => 'required',
                'template_id' => 'required',
                'model_id'    => 'required',
                'name'        => 'required',
                'startTime'   => 'required',
                'endTime'     => 'required',
            ], [
                'category.required'    => '请选择活动类型',
                'template_id.required' => '请选择活动模版',
                'model_id.required'    => '请选择活动模型',
                'name.required'        => '请输入活动名称',
                'name.startTime'       => '请输入活动开始时间',
                'name.endTime'         => '请输入活动结束时间',
            ]);
            $input = $request->request->all();

            $loginUser = $userService->getLoginUser();
            //投票中没有奖品
            $action = !empty($input['action']) ? $input['action'] : '';
            if ($action == 'redpack_rain') {
                $prizes = $input['prizes'];

                if (empty($prizes) || count($prizes) == 0) {
                    return $this->respondJson([
                        'code'    => ExceptionCode::GENERAL,
                        'message' => '请选择奖品',
                    ]);
                }
            }
            if($action == 'enroll' && !empty($input['rule'])){
                $input['rule']['showEnrollNumberOn'] = Arr::get($input, 'rule.showEnrollNumberOn', 'off');
            }

            $data = [
                'user_id'           => $loginUser['id'],
                'category'          => $input['category'],
                'template_id'       => $input['template_id'],
                'model_id'          => $input['model_id'],
                'name'              => $input['name'],
                'startTime'         => $input['startTime'],
                'endTime'           => $input['endTime'],
                'limit'             => isset($input['limit']) ? json_encode($input['limit']) : json_encode([]),
                'backgroundColor'   => isset($input['backgroundColor']) ? $input['backgroundColor'] : '',
                'backgroundImg'     => !empty($input['backgroundImg']) ? $storageService->storeAsImage($storageService->tomedia($input['backgroundImg']))['original'] : '',
                'description'       => $input['description'] ?: '',
                'ruleDescription'   => isset($input['ruleDescription']) ? $input['ruleDescription'] : '',
                'listBackgroundImg' => !empty($input['listBackgroundImg']) ? $storageService->storeAsImage($storageService->tomedia($input['listBackgroundImg']))['original'] : '',
                'rule'              => !empty($input['rule']) ? json_encode($input['rule']) : '{}',
                'app_url'           => !empty($input['app_url']) ? $input['app_url'] : '',
                'isPause'           => 1,
                'clicks'            => 0,
                'joins'             => 0,
                'winnings'          => 0,
            ];
            /*
            if (!isset($input['share']['isopen']) || $input['share']['isopen'] != 1) {
                if ($input['category'] == 1) {
                    $data['shares'] = json_encode([
                        'isopen' => 0,
                    ]);
                } else {
                    $input['share']['isopen'] = 1;
                }
            }
            */

//            if ($action == 'redpack_rain') {
                $validateRes = $this->validateShares($input['share'], $input['category']);
                if ($validateRes['code'] != 0) {
                    return $this->respondJson($validateRes);
                }
                if (!isset($data['shares'])) {
                    if (!empty($input['share']['icon']) && $storageService->isTmp($storageService->tomedia($input['share']['icon']))) {
                        $input['share']['icon'] = $storageService->storeAsImage($storageService->tomedia($input['share']['icon']))['original'];
                    }
                    if (!empty($input['share']['qrcode']) && $storageService->isTmp($input['share']['qrcode'])) {
                        $input['share']['qrcode'] = $storageService->storeAsImage($storageService->tomedia($input['share']['qrcode']))['original'];
                    }
                    $data['shares'] = json_encode($input['share']);
                }
//            } else {
                //$data['shares'] = json_encode([]);
//                $data['shares'] = \GuzzleHttp\json_encode($input['share']);
//            }

            $actionServer = $this->getInstanceof($action);
            if ($actionServer) {
                $data = array_merge($data, $actionServer->valide($input));
            }

            if (!isset($data['publishing_ways'])) {
                $data['publishing_ways'] = '{}';
            }
            $activities = $activityService->createActivity($data);
            $activityInfoService->createActivity([
                'id'   => $activities->id,
                'name' => $activities->name,
            ]);

            $app = Arr::get($input, 'app', []);
            $wechat = Arr::get($input, 'wechat', []);
            (new Publisher)->publish($activities->id, compact('app', 'wechat'));

            if ($action == 'redpack_rain') {
                foreach ($input['prizes'] as $prize) {
                    $item = [
                        'activity_id'         => $activities->id,
                        'prize_id'            => $prize['id'],
                        'winning_limit'       => $prize['winning_limit'],
                        'stock_limit'         => $prize['stock_limit'],
                        'surplus'             => $prize['stock_limit'],
                        'max_amount'          => isset($prize['max_amount']) ? $prize['max_amount'] : 0,
                        'winning_probability' => $prize['winning_probability'],
                    ];
                    $activityPrizeService->create($item);
                }
            }
            $activityService->updateActivityPrizeRecord($activities->id);

            //投票
            if ($action == 'vote') {
                $activity_demoid = $input['activity_demoid'];
                //投票更新候选人
                $voteCandidateRepository->update(['activity_id' => $activities->id], ['activity_id' => $activity_demoid]);
                //更新分组
                $voteGroupRepository->update(['activity_id' => $activities->id], ['activity_id' => $activity_demoid]);
            }
            return $this->respondJson([
                'activities' => $activities,
            ]);
        }
        $mts = $activityService->getModelTemplates();
        //return view('web.activity.add', [
          //  'activity'      => new Activity(),
           // 'mts'           => $mts,
            //'activity_pris' => [],
        //]);
        return $this->respondJson([
            'data'=>[
                'activity'      => new Activity(),
                'mts'           => $mts,
                'activity_pris' => [],
                ]
        ]);
    }

    public function getActivityRule(
        Request $request,
        StorageService $storageService,
        PrizeRecordService $prizeRecordService,
        ActivityModelTemplateService $activityModelTemplateService,
        ActivityModelService $activityModelService,
        ActivityService $activityService,
        VoteGroupService $groupService
    )
    {
        $id = $request->query->get('template_id');
        if (empty($id)) {//编辑活动
            $id = $request->query->get('id');//编辑活动
            $activity = $activityService->findOne($id);
            if (empty($activity)) {
                return abort(404);
            }
            $activity_pris = [];
            foreach ($activity->prizes as $row) {
                $prize = $row->prize;
                $row = $row->toArray();
                $row['name'] = $prize->name;
                $row['id'] = $prize->id;
                $row['background_image'] = $storageService->tomedia($prize->background_image);
                $lastPrizeRecord = $prizeRecordService->getLastOne([['prize_id', $row['prize_id']]]);
                if (!empty($lastPrizeRecord)) {
                    $row['available_stock'] = $lastPrizeRecord->summary + $row['stock_limit'];
                } else {
                    $row['available_stock'] = $row['stock_limit'];
                }
                if (in_array($prize->type_code, ['wechat', 'alipay'])) {
                    $row['type'] = 'redpack';
                } else {
                    $row['type'] = 'other';
                }

                $activity_pris[] = $row;
            }
            $modelRule = $activity->model->rule;
            $model = $activity->model;
            $template = null;

            //投票
            //$groupRes = $voteGroupRepository->where(['activity_id'=>$activity->id]);
            $groupRes = $groupService->getItemByActivityId($activity->id);
            if (count($groupRes)) {
                foreach ($groupRes as &$list) {
                    $list['group_id'] = $list->id;
                }
                $activity->groupIsopen = 1;
            } else {
                $activity->groupIsopen = 0;
            }
            $activity->group = $groupRes;
            $template = $activity->template;
        } else {//添加
            $template = $activityModelTemplateService->findOne($id);
            if (is_null($template)) {
                abort(404);
            }

            $model_id = $template->model_id;

            $model = $activityModelService->findOne($model_id);

            if (is_null($model)) {
                abort(404);
            }
            $activity = new Activity();
            $modelRule = $model->rule;
            $activity_pris = [];
        }
        if (empty($activity->rule)) {
            $activity->rule = '[]';
        }
        if($modelRule == "team-pk"){
            $modelRule = 'team_pk';
        }else if($modelRule == "prize-code"){
            $modelRule = 'prize_code';
        }
        return view('components.rules.' . $modelRule . '_rule', [
            'activity'         => $activity,
            'ativity_template' => $template,
            'ativity_model'    => $model,
            'activity_pris'    => $activity_pris,

        ]);
    }

    public function getActivityTplInfo(Request $request, ActivityModelTemplateService $templateService)
    {
        $tpl_id = $request->query->get('tpl');
        $tpl = $templateService->findOne($tpl_id);

        return $this->respondJson([
            'tpl' => $tpl,
        ]);
    }

    public function index(UserService $userService,ActivityModelService $activityModelService)
    {
        return view('web.activity.list');
    }

    public function quiz(UserService $user)
    {
        $profile = json_encode([
            'user-id'    => $user->getUserId(),
            'group-code' => $user->getGroupCode(),
        ]);
        return view('web.activity.quiz.iframeLayout', compact('profile'));
    }

    public function dadishu(UserService $user)
    {
        $profile = json_encode([
            'user-id'    => $user->getUserId(),
            'group-code' => $user->getGroupCode(),
        ]);
        return view('web.activity.dadishu.iframeLayout', compact('profile'));
    }

    public function prizeCode(UserService $user)
    {
        $profile = json_encode([
            'user-id'    => $user->getUserId(),
            'group-code' => $user->getGroupCode(),
        ]);
        return view('web.activity.prizeCode.iframeLayout', compact('profile'));
    }

    public function eatChicken(UserService $user)
    {
        $profile = json_encode([
            'user-id'    => $user->getUserId(),
            'group-code' => $user->getGroupCode(),
        ]);
        return view('web.activity.eatChicken.iframeLayout', compact('profile'));
    }

    public function activityLists(Request $request, ActivityService $activityService)
    {
        $this->validate($request, [
            'category' => 'required|integer',
            'offset'   => 'required|integer',
            'limit'    => 'required|integer',
            'sort'     => 'string',
            'order'    => 'string',
        ], [
            'category.required' => '活动类型未提交',
            'category.integer'  => '活动类型错误',
            'offset.required'   => '活动列表起始数提交',
            'offset.integer'    => '活动列表起始数类型错误',
            'limit.required'    => '活动列表页面数据条数未提交',
            'limit.integer'     => '活动列表页面数据条数类型错误',
            'sort.string'       => '活动列表排序字段类型错误',
            'order.string'      => '活动列表排序类型错误',
        ]);

        $category = intval($request->query->get('category', 0));
        $start = intval($request->query->get('offset', 0));
        $limit = intval($request->query->get('limit', 10));
        $keyword = $request->query->get('search');
        $sort = $request->query->get('sort', 'weight');
        $order = $request->query->get('order', 'desc');

        list($total, $activities) = $activityService->getActivityListByPage($category, $start, $limit, $sort, $order, $keyword);
        return $this->respondJson([
            'total' => $total,
            'rows'  => $activities,
        ]);
    }

    /**
     * 活动列表数据
     * @param Request $request
     * @param ActivityService $activityService
     * @return \Illuminate\Http\JsonResponse
     */
    public function activities(Request $request, ActivityService $activityService)
    {
        $this->validate($request, [
            'category' => 'required|integer',
            'offset'   => 'required|integer',
            'limit'    => 'required|integer',
            'sort'     => 'string',
            'order'    => 'string',
        ], [
            'category.required' => '活动类型未提交',
            'category.integer'  => '活动类型错误',
            'offset.required'   => '活动列表起始数提交',
            'offset.integer'    => '活动列表起始数类型错误',
            'limit.required'    => '活动列表页面数据条数未提交',
            'limit.integer'     => '活动列表页面数据条数类型错误',
            'sort.string'       => '活动列表排序字段类型错误',
            'order.string'      => '活动列表排序类型错误',
        ]);

        $category = intval($request->query->get('category', 0));
        $start = intval($request->query->get('offset', 0));
        $limit = intval($request->query->get('limit', 10));
        $keyword = $request->query->get('search');
        $sort = $request->query->get('sort', 'weight');
        $order = $request->query->get('order', 'desc');

        list($total, $activities) = $activityService->getActivityListByPage($category, $start, $limit, $sort, $order, $keyword);
        return $this->respondJson([
            'data' => [
                'total' => $total,
                'rows'  => $activities,
            ]
        ]);
    }

    /**
     * 获取活动初始化信息
     */
    public function getActivityApi(Request $request, ActivityService $activityService)
    {
        $id = $request->activity_id;
        if(!$id){
            return response()->failed('缺少关键参数：activity_id');
        }
        if(!Uuid::isValid($id)){
            return response()->failed('错误的活动id');
        }
        $activity_info = $activityService->findOne($id);
        $info=[
            'name'=>$activity_info->name,
            'category'=>$activity_info->category,
            'star_time'=>$activity_info->startTime,
            'end_time'=>$activity_info->endTime,
            'model_id'=>$activity_info->model_id,
            'template_id'=>$activity_info->template_id,
            'background_img'=>$activity_info->backgroundImg,
            'list_background_img'=>$activity_info->listBackgroundImg,
            'remark'=>$activity_info->remark,
            'description'=>$activity_info->description,
            'limits'=>json_decode($activity_info->limit),
            'rules'=>json_decode($activity_info->rule),
            'shares'=>json_decode($activity_info->shares),
            'publishing_ways'=>json_decode($activity_info->publishing_ways),
        ];
        return response()->success($info);
    }

    public function  createTemplate(
        ActivityModelService $activityServiceModel,
        ActivityModelTemplateService $template
    )
    {
        DB::beginTransaction();
        try{
            $params = [
                'activityModel'=>[
                    'name'=>'拼团',
                    'rule'=>'team-pk',
                    'type'=>''
                ],
                'templateModel'=>[
                    'model_id'  =>'',
                    'name'      =>'拼团',
                    'template'  =>'team-pk',
                    'thumb'     =>'/images/admin/team-pk.png',
                    'url'       =>'/act/team-pk/index.html',
                    'isBackgroundImage'=>1,
                    'isBackgroundColor'=>0
                ]
            ];
            $params['templateModel']['model_id'] = $activityServiceModel->create($params['activityModel'])->id;
            $template->create($params['templateModel']);
            DB::commit();
            return 'true<br/>'.$params['activityModel']['name'];
        }catch (\Exception $e){
            DB::rollBack();
            return $e;
        }


    }

    public function edit(
        Request $request,
        ActivityService $activityService,
        StorageService $storageService,
        ActivityInfoService $activityInfoService,
        ActivityPrizeService $activityPrizeService,
        PrizeRecordService $prizeRecordService,
        ActivityRecordService $activityRecordService,
        ActivityModelService $activityModelService
    )
    {
        $id = $request->input('id');
        $activity = $activityService->findOne($id);
        if (empty($activity)) {
            return abort(404);
        }
        if ($request->isMethod('post')) {
            $input = $request->request->all();

            if (isset($input['isPause'])) {
                $updates['isPause'] = $input['isPause'];

                $res = $activityService->saveActivity($updates, $id);

                //清除投票缓存数据$voteCandidateRepository
                if ($activity->model->rule == 'vote') {
                    if ($input['isPause'] == 1) {
                        event(new ActivityPaused($id)); //暂停
                    } elseif ($input['isPause'] == 0) {
                        event(new ActivityStarted($id)); //开始
                    }
                }

                $rule = $activity->model->rule;
                $toTrigger = \App\Entities\Activity::query()->find($id);
//                暂时屏蔽 php内存溢出
               switch ($rule) {
                    case 'shaking':
                        event(new ShakingUpdated($toTrigger));
                        break;
                    case 'roulette':
                        event(new RouletteUpdated($toTrigger));
                        break;
                    case 'scratch':
                        event(new ScratchUpdated($toTrigger));
                        break;
                    case 'golden-eggs':
                        event(new GoldenEggsUpdated($toTrigger));
                        break;
                   default:
                        event(new ActivityCommonUpdated($toTrigger));
                        break;
                }
                $this->updateActivityRedis($id);

                return $this->respondJson([
                    'code'    => ExceptionCode::SUCCESS_CODE,
                    'message' => '保存成功',
                ]);
            }
            $activityRecords = $activityRecordService->count([['activity_id', $id]]);
            if ($activityRecords > 0) {
                return $this->respondJson([
                    'code'    => ExceptionCode::GENERAL,
                    'message' => '该活动已有人参加，禁止编辑保存',
                ]);
            }
            $updates = $this->validateUpdates($input, $storageService);
            //投票中没有奖品
            $action = !empty($input['action']) ? $input['action'] : '';

            if ($action == 'vote') {
                $rule = [
                    'relevanceEnrollOn' => Arr::get($input, 'rule.relevanceEnrollOn', 'off'),
                    'relevanceEnroll'   => Arr::get($input, 'rule.relevanceEnroll'),
                    'showEnrollNumberOn' => Arr::get($input, 'rule.showEnrollNumberOn', 'off'),
                ];

                $updates['rule'] = json_encode($rule);
            }
            if($action == 'enroll' && isset($input['rule'])){
                $input['rule']['showEnrollNumberOn'] = Arr::get($input, 'rule.showEnrollNumberOn', 'off');
                $updates['rule'] = json_encode($input['rule']);
            }

            /*
            if ($action == 'vote') {
                $updates['shares'] = isset($updates['share']) ? json_encode($updates['share']) : '{}';
            }
            */
            $activityService->saveActivity($updates, $id);

            if (isset($updates['name'])) {
                $activityInfoService->modifyActivity(['name' => $updates['name']], [['id', $id]]);
            }

            if ($action == 'redpack_rain') {
                if (isset($input['prizes'])) {
                    if (empty($input['prizes']) || count($input['prizes']) == 0) {
                        return $this->respondJson([
                            'code'    => ExceptionCode::GENERAL,
                            'message' => '请选择奖品',
                        ]);
                    }

                    $activityPrizeService->delete([['activity_id', $id]]);
                    foreach ($input['prizes'] as $prize) {
                        $item = [
                            'activity_id'         => $id,
                            'prize_id'            => $prize['id'],
                            'winning_limit'       => $prize['winning_limit'],
                            'stock_limit'         => $prize['stock_limit'],
                            'surplus'             => $prize['stock_limit'],
                            'max_amount'          => isset($prize['max_amount']) ? $prize['max_amount'] : 0,
                            'winning_probability' => $prize['winning_probability'],
                        ];
                        $activityPrizeService->create($item);
                    }
                    $activityService->updateActivityPrizeRecord($id);
                }
            }


            $this->updateActivityRedis($id);
            $app = Arr::get($input, 'app', []);
            $wechat = Arr::get($input, 'wechat', []);
            (new Publisher)->publish($id, compact('app', 'wechat'));

            return $this->respondJson([
                'message' => '保存成功',
            ]);
        }

        $mts = $activityService->getModelTemplates();
        $activity_pris = [];
        foreach ($activity->prizes as $row) {
            $prize = $row->prize;
            $row = $row->toArray();
            $row['name'] = $prize->name;
            $row['id'] = $prize->id;
            $row['background_image'] = $storageService->tomedia($prize->background_image);
            $lastPrizeRecord = $prizeRecordService->getLastOne([['prize_id', $row['prize_id']]]);
            if (!empty($lastPrizeRecord)) {
                $row['available_stock'] = $lastPrizeRecord->summary + $row['stock_limit'];
            } else {
                $row['available_stock'] = $row['stock_limit'];
            }
            if (in_array($prize->type_code, ['wechat', 'alipay'])) {
                $row['type'] = 'redpack';
            } else {
                $row['type'] = 'other';
            }

            $activity_pris[] = $row;
        }
        $activity->model = $activityModelService->findOne($activity->model_id)->toArray();
//        return view('web.activity.add', [
//            'activity'      => $activity,
//            'mts'           => $mts,
//            'activity_pris' => $activity_pris,
//        ]);
        return $this->respondJson([
           'data'=>[
               'activity'       =>  $activity,
               'mts'            =>  $mts,
               'activity_pris'  =>  $activity_pris
           ]
        ]);
    }

    public function delete(UserService $user, Request $request, ActivityRepository $activityRepository, PrizeStockService $prizeStockService)
    {
        $this->validate($request, [
            'id' => 'required',
        ], [
            'id.required' => '活动ID不能为空',
        ]);
        $id = $request->input('id');
        $activity = $activityRepository->findGroupActivityById($id, $user->getGroupCode());
        if(empty($activity)){
            return $this->respondJson([
                'code'    => ExceptionCode::GENERAL,
                'message' => '活动不存在！',
            ]);
        }
        if ($activity->isPause()) {
            return $this->respondJson([
                'code'    => ExceptionCode::GENERAL,
                'message' => '活动正在进行中，请暂停后再删除！',
            ]);
        }
        $ret = $activity->delete();

        if ($ret) {
            $prizeStockService->recycleByActivity($activity);
            return $this->respondJson([
                'message' => '删除成功',
            ]);
        }

        return $this->respondJson([
            'code'    => ExceptionCode::GENERAL,
            'message' => '删除失败',
        ]);

    }

    public function getActivityPrizeStock(Request $request, ActivityService $activityService)
    {
        $activity_id = $request->query->get('id');
        if (empty($activity_id)) {
            return $this->respondJson([
                'code'    => ExceptionCode::GENERAL,
                'message' => '活动id不能为空',
            ]);
        }
        $list = $activityService->getActivityPrizeStock($activity_id);

        return $this->respondJson(['rows' => $list->toArray()]);
    }

    public function getActivityQrcode(
        Request $request,
        WechatService $service,
        ActivityService $activityService
    ) {
        $activity_id = $request->query->get('id');
        $activity = $activityService->findOne($activity_id);
        if (empty($activity)) {
            return '活动不存在';
        }
        $host = '';
        $activityTemplate = $activity->template;
        $activityModel = $activity->model;
        if ($activity->category == 2) {
            $hostUrl = config('api.host');
            if ($activityModel->rule == 'redpack_rain') {
                $string = base64_encode(json_encode(["activity_id" => $activity->id]));
                $host = $hostUrl . '/' . $activityModel->rule . '/activity/index/' . $string . '/';
            } else {
                $host = $hostUrl . $activityTemplate->url . '?act_id=' . $activity->id;
            }
        }

        $ways = \GuzzleHttp\json_decode($activity->publishing_ways, true);
        $ways = [
            'app' => [
                'is_open' => Arr::get($ways, 'app.is_open'),

                "app_urls" => Arr::get($ways, 'app.app_urls')
            ],
            'wechat' => [
                'is_open' => Arr::get($ways, 'wechat.is_open'),
                "qr_code" => Arr::get($ways, 'app.qr_code')
            ],
        ];
        $wechat = "没有设置授权账号";
        $wechat_auth = false;
        if (Arr::get($ways, 'wechat.is_open') == 'on') {
            $wechat = $service->makeSilentlyAuthorizedUrl($activity_id);
            //$wechat =config('api.host') . '/web/come/wechat?id' .$activity_id;
            $wechat_auth = true;
        }
        return $this->respondJson([
            'data'=>[
                'url'           =>  $host,
                'wechat'        =>  $wechat,
                'ways'          =>  $ways,
                'wechat_auth'   =>  $wechat_auth
            ]
        ]);

    }

    public function summaryTotal(ActivityService $activityService, UserService $userService, ActivityRecordService $activityRecordService)
    {
        $login_user = $userService->getLoginUser();
        $activities = $activityService->getActivitiesByUser($login_user['id']);
        $activity_ids = $activities->pluck('id')->toArray();
        $todayJoins = $activityRecordService->count([['activity_id', $activity_ids], ['created_at', '>=', date('Y-m-d 00:00:00')], ['created_at', '<', date("Y-m-d", strtotime("+1 day"))]]);
        $allJoins = $activityRecordService->count([['activity_id', $activity_ids]]);
        $allActivities = $activities->count();
        $inActivities = $activityService->countByConditions([['user_id', $login_user['id']], ['isPause', 0], ['startTime', '<=', date('Y-m-d H:i:s')], ['endTime', '>=', date('Y-m-d H:i:s')]]);

        return $this->respondJson([
            'data' => array(
                'tjoin'       => $todayJoins,
                'ajoin'       => $allJoins,
                'all_act'     => $allActivities,
                'ranning_act' => $inActivities,
            ),
        ]);
    }

    public function getUserActivityReports(ActivityService $activityService, UserService $userService, ActivityRecordService $activityRecordService)
    {
        $activities = $activityService->findByUserAndRunning($userService->getLoginUser()['id']);
        $list = [];
        foreach ($activities as $row) {
            $row = $row->toArray();
            $item = ['name' => $row['name'], 'id' => $row['id'], 'created_at' => $row['created_at']];
            $item['report'] = [];
            $clicks = $row['clicks'];
            $joins = $row['joins'];
            $winnings = $row['winnings'];
            $exchanges = $activityRecordService->count([['activity_id', $row['id']], ['is_exchange', 1]]);
            for ($i = 0; $i < 7; $i++) {
                $day = date("Y-m-d", strtotime('-' . ($i - 1) . " day"));
                $lastday = date("Y-m-d", strtotime('-' . $i . " day"));
                $joinUsers = $activityRecordService->countUserByConditions([['activity_id', $row['id']], ['created_at', '>', $lastday], ['created_at', '<', $day]]);
                $dayJoins = $activityRecordService->count([['activity_id', $row['id']], ['created_at', '>', $lastday], ['created_at', '<', $day]]);
                $winningUsers = $activityRecordService->countUserByConditions([['activity_id', $row['id']], ['created_at', '>', $lastday], ['created_at', '<', $day], ['prize_id', '!=', null]]);
                $dayWinnings = $activityRecordService->count([['activity_id', $row['id']], ['created_at', '>', $lastday], ['created_at', '<', $day], ['prize_id', '!=', null]]);
                $exchangeUsers = $activityRecordService->countUserByConditions([['activity_id', $row['id']], ['created_at', '>', $lastday], ['created_at', '<', $day], ['prize_id', '!=', null], ['is_exchange', 1]]);
                $dayExchanges = $activityRecordService->count([['activity_id', $row['id']], ['created_at', '>', $lastday], ['created_at', '<', $day], ['prize_id', '!=', null], ['is_exchange', 1]]);

                $day_join = [
                    'users'    => $joinUsers,
                    'num'      => $dayJoins,
                    'user_avg' => $dayJoins == 0 ? 0 : ($dayJoins / $joinUsers),
                ];
                $day_winnings = [
                    'users'    => $winningUsers,
                    'num'      => $dayWinnings,
                    'user_avg' => $dayWinnings == 0 ? 0 : ($dayWinnings / $winningUsers),
                ];
                $day_exchange = [
                    'users'    => $exchangeUsers,
                    'num'      => $dayExchanges,
                    'user_avg' => $dayExchanges == 0 ? 0 : ($dayExchanges / $exchangeUsers),
                ];
                $item['report']['join'][] = $day_join;
                $item['report']['winning'][] = $day_winnings;
                $item['report']['exchange'][] = $day_exchange;
            }

            $item['report']['funnel'] = [
                [
                    'name'  => '参与率',
                    'value' => ($clicks == 0 ? 0 : (sprintf("%.2f", $joins / $clicks) * 100)),
                ],
                [
                    'name'  => '中奖率',
                    'value' => ($joins == 0 ? 0 : (sprintf("%.2f", $winnings / $joins) * 100)),
                ],
                [
                    'name'  => '兑奖率',
                    'value' => ($winnings == 0 ? 0 : (sprintf("%.2f", $exchanges / $winnings) * 100)),
                ],
            ];

            $list[] = $item;
        }

        return $this->respondJson([
            'data' => $list,
        ]);
    }

    public function getUserActivityDashboardByUserId(
        ActivityService $activityService,
        ActivityInfoService $activityInfoService,
        UserService $user
    ){
        dd($user->getLoginUser());
    }

    /**
     * 用于活动统计下的查看详情   (数据详情报表)
     * @todo 待添加活动分享统计
     * @param Request $request
     * @param ActivityService $activityService
     * @param UserService $userService
     * @param ActivityRecordService $activityRecordService
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserActivityDashboardById(
        Request $request,
        ActivityService $activityService,
        UserService $userService,
        ActivityRecordService $activityRecordService
    )
    {
        if(!isset($request->id)) return $this->respondJson(['data'=>'error']);
        $activity = $activityService->findOne($request->id);
        if(!isset($activity)) return $this->respondJson(['data'=>'没有这个id']);
        $list = [];
        $list['activity'] = $activity;
        $YesterdayTime = date('Y-m-d',strtotime('-1 day'));
        //昨日到今日的数据
        $time = [$YesterdayTime.' 00:00:00',date('Y-m-d').' 23:59:59'];

        $new_record = $activityRecordService->getActivityRecordsByIdOrTime($activity->id,$time);
        $allRecord = $activityRecordService->getActivityRecordsByIdOrTime($activity->id);
        if (!$allRecord) {
            return $this->respondJson([
                'data' => null
            ]);
        }
        $allRecordUsers = array_unique_key($allRecord->toArray(),'openid');
        $all_exchange = $activityRecordService->count([['activity_id',$activity->id],['is_exchange',1]]);
        return $this->respondJson([
            'data' => [
                'activity'              =>  $activity,
                'new_record'            =>  count($new_record), //新参与次数
                'all_record'            =>  count($allRecord),  //所有参与次数
                'all_record_users'      =>  count($allRecordUsers), //所有参与用户数
                'all_exchange'          =>  $all_exchange   //所有兑奖用户数
            ]
        ]);
    }

    /**
     * 活动统计页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function ActivityStatistics(
        Request $request
    ) {
        return view('web.activity.ActivityStatistics');
    }

    private function validateUpdates($input, StorageService $storageService, $updates = [])
    {
        if (isset($input['name'])) {
            $updates['name'] = $input['name'];
        }
        if (isset($input['startTime'])) {
            $updates['startTime'] = $input['startTime'];
        }
        if (isset($input['endTime'])) {
            $updates['endTime'] = $input['endTime'];
        }
        if (isset($input['limit'])) {
            $updates['limit'] = json_encode($input['limit']);
        }
        if (isset($input['backgroundColor'])) {
            $updates['backgroundColor'] = $input['backgroundColor'];
        }
        if (isset($input['backgroundImg']) && $input['backgroundImg'] != null) {
            /*
            if (!empty($input['backgroundImg']) && $storageService->isTmp($storageService->tomedia($input['backgroundImg']))) {
                $input['backgroundImg'] = $storageService->storeAsImage($storageService->tomedia($input['backgroundImg']))['original'];
            }*/
            $updates['backgroundImg'] = $input['backgroundImg'];
        } else {
            $updates['backgroundImg'] = '';
        }

        if (isset($input['listBackgroundImg'])) {
            if (!empty($input['listBackgroundImg']) && $storageService->isTmp($storageService->tomedia($input['listBackgroundImg']))) {
                $input['listBackgroundImg'] = $storageService->storeAsImage($storageService->tomedia($input['listBackgroundImg']))['original'];
            }
            $updates['listBackgroundImg'] = $input['listBackgroundImg'];
        }
        if (isset($input['description'])) {
            $updates['description'] = $input['description'];
        }
        if (isset($input['ruleDescription'])) {
            $updates['ruleDescription'] = $input['ruleDescription'];
        }
        if (isset($input['rule'])) {
            $updates['rule'] = json_encode($input['rule']);
        }
        if (isset($input['isPause'])) {
            $updates['isPause'] = $input['isPause'];
        }
        if (isset($input['clicks'])) {
            $updates['clicks'] = $input['clicks'];
        }
        if (isset($input['joins'])) {
            $updates['joins'] = $input['joins'];
        }
        if (isset($input['winnings'])) {
            $updates['winnings'] = $input['winnings'];
        }
        if (isset($input['share'])) {
            if (!empty($input['share']['icon']) && $storageService->isTmp($storageService->tomedia($input['share']['icon']))) {
                $input['share']['icon'] = $storageService->storeAsImage($storageService->tomedia($input['share']['icon']))['original'];
            }
            if (!empty($input['share']['qrcode']) && $storageService->isTmp($storageService->tomedia($input['share']['qrcode']))) {
                $input['share']['qrcode'] = $storageService->storeAsImage($storageService->tomedia($input['share']['qrcode']))['original'];
            }
            $updates['shares'] = json_encode($input['share']);
        }
        if (isset($input['app_url'])) {
            $updates['app_url'] = $input['app_url'];
        } else {
            $updates['app_url'] = '';
        }

        $action = !empty($input['action']) ? $input['action'] : '';
        $actionServer = $this->getInstanceof($action);
        if ($actionServer) {
            $updates = array_merge($updates, $actionServer->valide($input));
        }

        return $updates;
    }

    private function validateShares($shares, $category = 1)
    {
        if (!isset($shares['isopen'])) {
            return ['code' => 0];
        }
        //if (($shares['isopen'] != 1 || $shares['isopen'] != 'on') && $category == 1) {
        if (($shares['isopen'] != 1 || $shares['isopen'] != 'on')) {
            return ['code' => 0];
        }
        if (empty($shares['icon'])) {
            return ['code' => ExceptionCode::GENERAL, 'message' => '请上传分享图标'];
        }
        if (empty($shares['title'])) {
            return ['code' => ExceptionCode::GENERAL, 'message' => '请输入分享标题'];
        }
        if (empty($shares['content'])) {
            return ['code' => ExceptionCode::GENERAL, 'message' => '请输入分享描述'];
        }

        return ['code' => 0];
        if ($category == 1) {
            if (empty($shares['qrcode'])) {
                return ['code' => ExceptionCode::GENERAL, 'message' => '请上传分享展示二维码'];
            }
        } else {
            if (!empty($shares['landindPage'])) {
                if ($shares['landindPage'] == 1) {
                    if (empty($shares['qrcode'])) {
                        return ['code' => ExceptionCode::GENERAL, 'message' => '请上传活动落地页底部图片'];
                    }
                    if (empty($shares['download']['ios'])) {
                        return ['code' => ExceptionCode::GENERAL, 'message' => '请输入ios下载地址'];
                    }
                    if (empty($shares['download']['android'])) {
                        return ['code' => ExceptionCode::GENERAL, 'message' => '请输入android下载地址'];
                    }
                } else {
                    if (empty($shares['share_url'])) {
                        return ['code' => ExceptionCode::GENERAL, 'message' => '请输入自定义落地页面'];
                    }
                }
            }
        }

        return ['code' => 0];
    }

    /**
     * @param $activity_id
     *
     */
    private function updateActivityRedis($activity_id)
    {
        $redis = Redis::connection();
        $res = $redis->hDel('activityDetail', $activity_id);
    }

    /**
     * 投票大屏
     *
     * @param Request              $request
     * @param VoteCandidateService $voteCandidateService
     * @param VoteGroupService     $voteGroupService
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function voteDP(Request $request, VoteCandidateService $voteCandidateService, VoteGroupService $voteGroupService)
    {
        $activity_id = $request->input('activity_id');
        if (!$activity_id) {
            return $this->respondJson([
                'code'    => ExceptionCode::GENERAL,
                'message' => '活动id不能为空',
            ]);
        }
        $groups = $voteGroupService->getItemByActivityId($activity_id);
        $data = [];
        if ($groups->count() > 0) {
            $i = 0;
            foreach ($groups as $k => $group) {
                $groupId = $group->id;
                $items = $voteCandidateService->getItemsByGroup($groupId, $activity_id, 3);
                if ($items->count() <= 0) {
                    continue;
                }
                foreach ($items as $key => $item) {
                    $data[$i][$key]['group_name'] = $group->title;
                    $data[$i][$key]['title'] = $item->title;
                    $data[$i][$key]['voteNumber'] = $item->votes_number;
                }
                $i++;
            }
        }
        $color = ["#bc0402", "#ec7a00", "#01ec39"];
        $json = \GuzzleHttp\json_encode(['vote_data' => $data, 'color' => $color, 'dataLen' => count($data)]);

        return view('app.vote.unregister.index', ['json' => $json]);
    }

    public function changeWeight(Request $request,ActivityServiceModel $activityService){
        $activityId = $request->input('id');
        $weightNumber = $request->input('weight');
        if (!Uuid::isValid($activityId) || !is_numeric($weightNumber)) {
            return response()->failed('不是合法的activity_id/weight');
        }
        $result = $activityService->saveActivityById(['weight'=>$weightNumber],$activityId);
        if($result){
            return response()->success('操作成功');
        }else{
            return response()->failed('操作失败');
        }
    }

    public function getVoteRecords(Request $request, ActivityService $activityService){
        $activity_id = $request->input('activity_id');
        $vote_item = $request->input('title');
        $device_id = $request->input('device');
        $begin_time = $request->input('begin_time');
        $end_time = $request->input('end_time');
        $offset = $request->input('offset');
        $limit = $request->input('limit');
        $dataRes = $activityService -> getVoteRecords($activity_id,$device_id,$vote_item,$begin_time,$end_time,$limit,$offset);
        if (isset($dataRes['rows'])) {
            foreach ($dataRes['rows'] as $key => &$list) {
                $list->voted_at = isset($list->voted_at) ? date('Y-m-d H:i:s', $list->voted_at) : '';
            }
        }

        return $this->respondJson($dataRes);
    }

    public function exportVoteRecords(Request $request, ActivityService $activityService){
        $activity_id = $request->input('activity_id');
        $device_id = $request->input('device');
        $vote_item = $request->input('title');
        $begin_time = $request->input('begin_time');
        $end_time = $request->input('end_time');
        $activity = $activityService->findOne($activity_id);
        $dataRes = $activityService -> getVoteRecords($activity_id,$device_id,$vote_item,$begin_time,$end_time,0,0,true);
        if (empty($dataRes) || empty($activity)) {
            return Excel::create('empty', function ($excel) {
                $excel->sheet('sheet1', function ($sheet) {
                    $sheet->fromArray([]);
                });
            })->download('xlsx');
        }
        //组装数据
        foreach ($dataRes as $list) {
            $res['投票人'] = $list->username ? $list->username : '11';
            $res['手机号'] = $list->mobile ? $list->mobile : '';
            $res['投票时间'] = $list->voted_at ? date('Y-m-d H:i:s',$list->voted_at) : '';
            $res['投票对象'] = $list->title ? $list->title : '';
            $res['投票设备'] = $list->device_id ? $list->device_id : '';
            $res['投票IP'] = $list->ip ? $list->ip : '';
            $res['投票人所在地区'] = $list->location ? $list->location : '';
            $data[] = $res;
        }

        $filename = '【' . $activity->name . '】投票记录' . date('Y-m-d H:i:s');

        Excel::create($filename, function ($excel) use ($data) {
            $excel->sheet('投票记录', function ($sheet) use ($data) {
                $sheet->fromArray($data);
            });
        })->download('xlsx');
    }
}
